<template>
  <div>
    <navigation-bar>
      <div class="searchContent">
        <el-input
          v-model="roleName"
          placeholder="请输入角色名"
          size="mini"
          style="width: 150px; margin-right: 10px"
        ></el-input>
        <custom-button
          type="search"
          style="margin-right: 10px"
          @searchClick="searchClick"
        ></custom-button>
        <custom-button
          type="reset"
          style="margin-right: 10px"
          @resetClick="resetClick"
        ></custom-button>
        <custom-button
          type="add"
          style="margin-right: 10px"
          @addClick="addClick"
        ></custom-button>
      </div>
    </navigation-bar>
    <table-index
      :dataSource="dataSource"
      :tableColumns="tableColumns"
      :btnList="btnList"
      :pageSize="pageSize"
      :pageCount="pageCount"
      :pageNo="pageNo"
      @pageChange="pageChange"
      @editRow="editRow"
      @viewRow="viewRow"
      @deleteRow="deleteRow"
      btnListWidth="80"
      :selection="false"
      @handleSelectionChange="handleSelectionChange"
      @relationUserRow="relationUserRow"
    ></table-index>

    <div v-if="dialogShow">
      <custom-dialog
        :title="dialogTitle"
        size="large"
        @dialogClose="dialogClose"
      >
        <form-index
          :formConfig="formConfig"
          @submit="submit"
          :type="type"
          @formInputChange="formInputChange"
          ref="form"
        >
        </form-index>
      </custom-dialog>
    </div>

    <div v-if="dialogSelectUser">
      <custom-dialog
        title="选择用户"
        size="large"
        @dialogClose="dialogSelectClose"
      >
        <div class="singleTable">
          <singleTable
            :dataSource="userDatasource"
            :tableColumns="userTableColumns"
            height="500px"
            :selectItems="userSelect"
            @singleHandleSelectionChange="singleHandleSelectionChange"
          ></singleTable>
        </div>
        <div class="singleBtn">
          <el-button
            size="small"
            type="primary"
            style="margin-right: 10px; color: #fff"
            @click="singleBtnClick"
          >
            <i class="el-icon-check"></i> 勾选确定
          </el-button>
        </div>
      </custom-dialog>
    </div>
  </div>
</template>

<script>
import { roleForm } from "@/assets/form/managementCenter/systemManage/roleForm";
import customDialog from "@/components/customComponents/customDialog";
import customButton from "@/components/customComponents/customForm/customButton";
import formIndex from "@/components/customComponents/customForm/formIndex";
import singleTable from "@/components/customComponents/customeTable/singleTable.vue";
import tableIndex from "@/components/customComponents/customeTable/tableIndex";
import navigationBar from "@/components/customComponents/managementCenter/navigationBar";
import { AjaxCommon } from "@/libs/apiCommon";
import { PopupCommon } from "@/libs/popupCommon";
import { SessionCommon } from "@/libs/sessionCommon";
export default {
  components: {
    navigationBar,
    customButton,
    tableIndex,
    customDialog,
    formIndex,
    singleTable,
  },
  data() {
    return {
      roleId: "",
      userDatasource: [],
      userTableColumns: [
        {
          prop: "uLoginName",
          label: "用户帐号",
        },
        {
          prop: "uRealName",
          label: "用户名称",
        },
      ],
      userSelect: [],
      dialogSelectUser: false,
      roleName: "",
      // table 相关参数  begin
      dataSource: [],
      tableColumns: [
        {
          prop: "Name",
          label: "角色名",
        },
        {
          prop: "Description",
          label: "描述",
        },
      ],
      btnList: ["relationUser"],
      pageSize: 20,
      pageCount: 100,
      pageNo: 1,
      // table 相关参数  end

      // 弹窗是否显示
      dialogShow: false,
      // 弹窗标题 (新增修改不同)
      dialogTitle: "",

      // form的配置信息
      formConfig: roleForm,
      type: "add",
    };
  },
  methods: {
    getUserListByRoleId() {
      let self = this;
      AjaxCommon(
        `/api/UserRole/GetUserByRoleId?RoleId=${self.roleId}`,
        "get",
        null
      ).then((res) => {
        console.log(res, "res...............");
        var data = res.data;
        self.userSelect = data;
      });
    },
    singleBtnClick() {
      if (this.userSelect.length == 0) {
        PopupCommon.notify("info", "请选择至少一个用户");
        return;
      }
      // 循环新增
      this.userSelect.forEach((e) => {
        var userId = e.uID;
        AjaxCommon(
          `/api/UserRole/AddUserRole?uid=${userId}&rid=${this.roleId}`,
          "get",
          null
        ).then((res) => {
          console.log(res, "res...............");
        });
      });
      PopupCommon.notify("success", "操作成功");
      this.dialogSelectUser = false;
    },
    singleHandleSelectionChange(e) {
      this.userSelect = e;
    },
    dialogSelectClose() {
      this.dialogSelectUser = false;
    },
    handleSelectionChange(d) {
      console.log(d, "d...");
    },
    async relationUserRow(d) {
      this.roleId = d.data.Id;
      let self = this;
      await this.getUserListByRoleId();
      // 获取用户
      AjaxCommon("/api/User/Get", "get", null).then((res) => {
        var data = res.data.response.data;
        data.map((t) => {
          t.Id = t.uID;
        });
        console.log(data);
        self.userDatasource = data;
        self.dialogSelectUser = true;
      });
    },
    formInputChange(e) {
      // if (e.filedName == "idCard") {
      // 	const data = CardId.getInfoByCardId(e.value)
      // 	if (data) {
      // 		let newData = e.allData
      // 		newData["birthday"] = data.birthday
      // 		newData["sex"] = data.sex
      // 		this.$refs.form.changeFormValue(newData)
      // 	}
      // }
      console.log(e);
    },
    submit(d) {
      console.log(d);
      let self = this;
      console.log(d);
      if (d.Id) {
        AjaxCommon("/api/Role/Post", "post", d)
          .then((res) => {
            if (res.data.status == 200) {
              PopupCommon.notify("success", "操作成功");
              self.initPage();
              self.dialogClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          })
          .catch((err) => {
            PopupCommon.notify("error", err.message);
          });
      } else {
        delete d.Id;
        AjaxCommon("/api/Role/Post", "post", d)
          .then((res) => {
            if (res.data.status == 200) {
              PopupCommon.notify("success", "操作成功");
              self.initPage();
              self.dialogClose();
            } else {
              PopupCommon.notify("error", res.data.msg);
            }
          })
          .catch((err) => {
            PopupCommon.notify("error", err.message);
          });
      }
    },
    dialogClose() {
      this.dialogShow = false;
    },
    searchClick() {
      this.pageNo = 1;
      this.initPage();
    },
    resetClick() {
      this.roleName = "";
    },
    addClick() {
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = "";
          }
        });
      });
      this.formConfig = formConfigItem;
      this.type = "add";
      this.dialogShow = true;
      this.dialogTitle =
        "新增" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    // 分页点击事件
    pageChange(p) {
      this.pageNo = p;
      this.initPage();
    },
    editRow(d) {
      this.type = "edit";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "编辑" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    viewRow(d) {
      this.type = "look";
      let formConfigItem = this.formConfig;
      formConfigItem.map((t) => {
        Object.keys(t).map((res) => {
          if (res == "fieldName") {
            t.filedValue = d.data[t[res]];
          }
        });
      });
      this.formConfig = formConfigItem;
      this.dialogShow = true;
      this.dialogTitle =
        "查看" + JSON.parse(SessionCommon.getCurrentMenuInfo()).title;
    },
    deleteRow(d) {
      console.log(d);
      const id = d.data.id;
      let self = this;
      AjaxCommon("/ccdc/cfg/device/device/delete?id=" + id, "delete", {
        optReason: d.optReason,
      }).then((res) => {
        console.log(res, "res...............");
        if (res.data.code == 200) {
          PopupCommon.notify("success", "删除成功");
          self.initPage();
          self.dialogClose();
        } else {
          PopupCommon.notify("error", res.data.message);
        }
      });
    },
    // 初始化事件
    initPage() {
      let self = this;
      var params = `?page=${this.pageNo}&key=${this.roleName}`;
      AjaxCommon(`/api/Role/Get${params}`, "get", null).then((res) => {
        console.log(res, "res......");
        if (res.data.status == 200) {
          self.dataSource = res.data.response.data;
          self.pageCount = res.data.response.dataCount;
        } else {
          PopupCommon.notify("error", res.data.message);
        }
      });
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initPage();
    });
  },
};
</script>

<style>
.singleTable {
  margin-bottom: 20px;
}
.singleBtn {
  position: absolute;
  bottom: 8px;
  right: 9px;
}
</style>
